<template>
  <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :before-close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="默认配置" prop="default">
            <el-input v-model="form.default" placeholder="请填写默认配置:0否,1是" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="版本号" prop="version">
            <el-input v-model="form.version" placeholder="请输入版本号,多个用逗号隔开" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-query-row :label="'配置'" :labelWidth="80" style="margin-bottom:0;">
        <el-col :span="10">
          <textarea v-model="form.textarea" :style="`height:302px;resize: none;`" placeholder="请输入内容" class="el-textarea__inner"></textarea>
        </el-col>
        <el-col :span="14">
          <b-code-editor v-model="form.jsonStr" :indent-unit="2" :height="`302px`" style="border: #C0C4CC 1px solid;" />
        </el-col>
      </el-query-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    title: {
      default: '新增单版本配置',
      type: String
    },
    open: {
      default: false,
      type: Boolean
    },
    callback: {
      type: Function
    }
  },
  data () {
    return {
      form: {
        default: '',
        version: '',
        textarea: '',
        jsonStr: '{}'
      },
      rules: {
        default: [{ required: true, message: '默认配置不能为空', trigger: 'change' }],
        version: [{ required: true, message: '版本号不能为空', trigger: 'change' }],
      }
    }
  },
  watch: {
    'form.textarea' (value) {
      try {
        if(JSON.parse(value.trim())) {
          this.form.jsonStr = JSON.stringify(JSON.parse(value),null,2)
        }
      } catch (e) {
        console.log(e)
        this.form.jsonStr = `{}`
      }
    }
  },
  methods: {
    submitForm () {
      let vm = this
      vm.$refs["form"].validate(valid => {
        if (valid) {
          let { textarea, jsonStr, ...params } = vm.form;
          params.value = JSON.parse(jsonStr.replace(/[ ]|[\r\n]/g, ''));
          vm.callback(params);
          vm.cancel();
        }
      });
    },
    _resetForm () {
      let vm = this;
      vm.form = {
        default: 1,
        version: '',
        textarea: '',
        jsonStr: '{}'
      };
    },
    cancel () {
      this.$emit('update:open', false)
    }
  }
}
</script>
